<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>拖拽（边界判断）</title>
    <style>
        * {
            padding: 0;
            margin: 0;
        }

        .box {
            position: fixed;
            top: 50%;
            left: 50%;
            transform: translate(-50%,-50%);
            width:300px;
            height: 200px;
            background-color: pink;
        }
    </style>
</head>

<body>
    <div class="box"></div>
</body>
<script>
    let box = document.querySelector('.box');
    function move(a,x,y) {
        if (a) {
            document.onmousemove = (e) => {
                let boxWidth = (box.clientWidth / 2);
                let boxHeight = (box.clientHeight / 2);
                let viewWidth = document.documentElement.clientWidth;
                let viewHeight = document.documentElement.clientHeight;
                
                box.style['left'] = e.clientX + (boxWidth - x) + 'px';
                box.style['top'] = e.clientY + (boxHeight - y) + 'px';
                
                // 上
                if (box.offsetTop - boxHeight <= 0) {
                    box.style['top'] = boxHeight + 'px';
                }
                // 左
                if (box.offsetLeft - boxWidth <= 0) {
                    box.style['left'] = boxWidth + 'px';
                }
                // 下
                if (box.offsetTop + boxHeight >= viewHeight) {
                    box.style['top'] = viewHeight - boxHeight + 'px';
                }
                // 右
                if (box.offsetLeft + boxWidth >= viewWidth) {
                    box.style['left'] = viewWidth - boxWidth + 'px';
                }
            }
        } else {
            document.onmousemove = null;
        }
    }
    box.addEventListener('mousedown', function (e) {
        // 鼠标按下时在box内的坐标
        let downX = e.offsetX;
        let downY = e.offsetY;
        move(true,downX,downY);
    });
    box.addEventListener('mouseup', function () {
        move(false);
    });
</script>

</html>